package com.beeantec.jnrerc.modules.common.controller;

import com.beeantec.jnrerc.core.api.ApiRest;
import com.beeantec.jnrerc.core.api.controller.BaseController;
import com.beeantec.jnrerc.core.constants.Constant;
import com.beeantec.jnrerc.core.utils.SystemUtil;
import com.beeantec.jnrerc.dto.MemberVo;
import com.beeantec.jnrerc.entity.Member;
import com.beeantec.jnrerc.modules.member.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 课程音视频上传接口
 *
 * @author anthony
 */

@Api(value = "上传图片/文件/接口", tags = "上传图片/文件/接口")
@RestController
@RequestMapping(value = "/api/upload")
public class FileUploadController  extends BaseController {

    @Autowired
    private MemberService memberService;

    /**
     * 上传图片接口
     *
     * @param picFile
     * @author anthony
     */
    @ApiOperation(value = "上传用户头像", notes = "上传用户头像")
    @RequestMapping(value = "/headpic", method = RequestMethod.POST)
    public ApiRest<String> uploadPic(MultipartFile picFile,@RequestHeader("token") String token) {
        MemberVo memberVo = memberService.token(token);
        if (null==memberVo){
            return failure("用户不存在");
        }
        Member member = memberService.getById(memberVo.getMemberId());

        if (picFile == null || picFile.isEmpty()) {
            return super.failure("请文件进行上传");
        }
        // 获取上传文件的原名
        String fileName = picFile.getOriginalFilename();
        // 1、上传到本地
        File targetFile = null;
        boolean fileStatus = true;
        List<String> fileDocTypes = Arrays.asList("png","jpg","jpeg","gif");
        for (String filetype : fileDocTypes) {
            // 上传文件的原名+小写+后缀
            if (fileName.toLowerCase().endsWith(filetype)) {
                fileStatus = false;
                targetFile = new File(
                        SystemUtil.PIC_STORAGE_PATH + fileName);
                targetFile.setLastModified(System.currentTimeMillis());// 设置最后修改时间
                member.setAvatarUrl(Constant.BASE_SERVER+"/image/"+ fileName );
                break;
            }
        }
        if (fileStatus) {
            return super.failure("上传的文件类型不正确");
        }
        // 判断文件目录是否存在，不存在就创建文件目录
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        try {
            picFile.transferTo(targetFile);
        } catch (Exception e) {
            return super.failure("上传文件出错，请重新上传");
        }
        boolean result = memberService.saveOrUpdate(member);
        if (result){
            return success(member.getAvatarUrl());
        }
        return failure("更新头像失败");
    }


    /**
     * 上传图片接口
     *
     * @param picFile
     * @author anthony
     */
    @ApiOperation(value = "上传图片", notes = "上传图片")
    @RequestMapping(value = "/cover", method = RequestMethod.POST)
    public ApiRest<String> uploadCover(MultipartFile picFile) {
        if (picFile == null || picFile.isEmpty()) {
            return super.failure("请文件进行上传");
        }
        // 获取上传文件的原名
        String fileName = picFile.getOriginalFilename();
        // 1、上传到本地
        File targetFile = null;
        boolean fileStatus = true;
        List<String> fileDocTypes = Arrays.asList("png","jpg","jpeg","gif");
        for (String filetype : fileDocTypes) {
            // 上传文件的原名+小写+后缀
            if (fileName.toLowerCase().endsWith(filetype)) {
                fileStatus = false;
                targetFile = new File(
                        SystemUtil.PIC_STORAGE_PATH + fileName);
                targetFile.setLastModified(System.currentTimeMillis());// 设置最后修改时间
                break;
            }
        }
        if (fileStatus) {
            return super.failure("上传的文件类型不正确");
        }
        // 判断文件目录是否存在，不存在就创建文件目录
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        try {
            picFile.transferTo(targetFile);
        } catch (Exception e) {
            return super.failure(e.getMessage());
        }
        return success(Constant.BASE_SERVER+"/image/"+ fileName);
    }


    /**
     * 上传多媒体
     *
     * @param picFile
     * @author anthony
     */
    @ApiOperation(value = "上传多媒体", notes = "上传多媒体")
    @RequestMapping(value = "/media", method = RequestMethod.POST)
    public ApiRest<String> uploadMedia(MultipartFile picFile) {
        if (picFile == null || picFile.isEmpty()) {
            return super.failure("请文件进行上传");
        }
        String mediaRoot = "video";
        // 获取上传文件的原名
        String fileName = picFile.getOriginalFilename();
        // 1、上传到本地
        File targetFile = null;
        boolean fileStatus = true;

        List<String> fileVideoTypes = Arrays.asList("avi", "mp4", "flv", "mpg", "mov", "asf", "3gp", "f4v", "wmv",
                "x-ms-wmv\n");
        List<String> fileAudioTypes = Arrays.asList("mp3");

        for (String filetype : fileVideoTypes) {
            // 上传文件的原名+小写+后缀
            if (fileName.toLowerCase().endsWith(filetype)) {
                fileStatus = false;
                targetFile = new File(
                        SystemUtil.PERIOD_VIDEO_PATH + fileName);
                targetFile.setLastModified(System.currentTimeMillis());// 设置最后修改时间
                mediaRoot = "video";
                break;
            }
        }
        for (String filetype : fileAudioTypes) {
            // 上传文件的原名+小写+后缀
            if (fileName.toLowerCase().endsWith(filetype)) {
                fileStatus = false;
                targetFile = new File(
                        SystemUtil.PERIOD_AUDIO_PATH + fileName);
                targetFile.setLastModified(System.currentTimeMillis());// 设置最后修改时间
                mediaRoot = "audio";
                break;
            }
        }
        if (fileStatus) {
            return super.failure("上传的文件类型不正确");
        }
        // 判断文件目录是否存在，不存在就创建文件目录
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        try {
            picFile.transferTo(targetFile);
        } catch (Exception e) {
            return super.failure(e.getMessage());
        }
        return success(Constant.BASE_SERVER+"/"+mediaRoot+"/"+ fileName);
    }
}
